package com.ykdl.member.kid.set;

import java.util.ArrayList;
import java.util.List;

import oauth.signpost.http.HttpParameters;
import net.wxxr.dataparse.model.DataParseError;
import net.wxxr.dataparse.model.DataState;
import net.wxxr.http.interfaces.ITag;
import net.wxxr.http.request.HttpBaseRequest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.BitmapUtils;
import com.ykdl.member.AppManager;
import com.ykdl.member.kid.R;
import com.ykdl.member.base.service.DownloadAPK;
import com.ykdl.member.constant.KidConfig;
import com.ykdl.member.kid.beans.AppBean;
import com.ykdl.member.kid.beans.AppListBean;
import com.ykdl.member.kid.beans.GetUser_ScoreBean;
import com.ykdl.member.kid.gears.BaseScreen;
import com.ykdl.member.kid.image.ImageOptionsFactory;
import com.ykdl.member.kid.marketcard.CardPersonalInformationActivity;
import com.ykdl.member.kid.marketcard.ChangeStateActivity;
import com.ykdl.member.kid.marketcard.PersonalDataActivity;
import com.ykdl.member.kid.prefs.IAskMyActionPre;
import com.ykdl.member.kid.prefs.UpdatePrefs;
import com.ykdl.member.kid.regandlogin.RegAndLoginActivity;
import com.ykdl.member.kid.regandlogin.StateSelectActivity;
import com.ykdl.member.kid.util.AccessTokenKeeper;
import com.ykdl.member.kid.util.MobileUtils;
import com.ykdl.member.kid.util.VersionUdgrateUtil;
import com.ykdl.net.manager.TaskManager;
import com.ykdl.net.manager.Wxxr;

public class SettingActivity extends BaseScreen implements OnClickListener, OnItemClickListener{
	
	public static final String TAG = SettingActivity.class.getSimpleName();
	
	private AlertDialog dialog;
	private Button smsForward, mailForward, mCancle;
	private TextView unregister, regist_function,set_newversion;
	// ArrayLisAppInfor
	final static int GET_APP_OK = 10;
	private LayoutInflater layoutInflater;
	private OtherAppAdapter otheappadapter;
	private OurAppAdapter ourappadapter;
	//private AppItemClick appitemClick;
	private TextView ourapploading, otherapploading,now_state;
	
	private Button mBtnLoginRegist, mBtnLogon;
	private RelativeLayout set_psuh_rl ;
	private AccessTokenKeeper mTokenKeeper;
	private ListView mOurList;
	private BitmapUtils mBmpUtils;
	private VersionUdgrateUtil versionUdgrateUtil;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTopTitle("设置", 0, R.drawable.back_bg, new OnClickListener() {

			@Override
			public void onClick(View v) {
//				go(HomeActivity.class);
				finish();
			}
		}, 0, 0, null, R.drawable.title_bg, false);
		setContent(R.layout.settingactivity_xml);
		findViewByIds();
		mBmpUtils = new BitmapUtils(this);
		layoutInflater = this.getLayoutInflater();
		ourappadapter = new OurAppAdapter();
		
		mOurList = ((ListView) findViewById(R.id.set_our_app));
		mOurList.setAdapter(ourappadapter);
		mOurList.setOnItemClickListener(this);
		((ListView) findViewById(R.id.set_other_app)).setAdapter(otheappadapter);
		// ourapploading = (TextView) findViewById(R.id.us_apploading);
		otherapploading = (TextView) findViewById(R.id.other_apploading);
		findViewById(R.id.two_email).setOnClickListener(this);// 给客服发邮件
		findViewById(R.id.two_phone).setOnClickListener(this);// 给客服打电话
		findViewById(R.id.set_aboutus_div).setOnClickListener(this);// 免责
		findViewById(R.id.setting_aboutus).setOnClickListener(this);
		mBtnLoginRegist = (Button) findViewById(R.id.btnLoginRegist);
		mBtnLoginRegist.setOnClickListener(this);
		mBtnLogon = (Button) findViewById(R.id.btnLogon);
		mBtnLogon.setOnClickListener(this);
		mTokenKeeper = new AccessTokenKeeper(this);
		boolean isAnonymous = mTokenKeeper.getmisAnonymous();
		if (isAnonymous) {
			mBtnLoginRegist.setVisibility(View.VISIBLE);
			mBtnLogon.setVisibility(View.GONE);
			findViewById(R.id.set_regdiv).setVisibility(View.GONE);
			findViewById(R.id.set_ibb).setVisibility(View.GONE);
			set_psuh_rl.setVisibility(View.GONE);
		} else {
			mBtnLoginRegist.setVisibility(View.GONE);
			mBtnLogon.setVisibility(View.VISIBLE);
			set_psuh_rl.setVisibility(View.VISIBLE);
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		getData();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	private void showUpdateDialog() {
		new AlertDialog.Builder(SettingActivity.this).setTitle(R.string.fordoctitle).setMessage(UpdatePrefs.getDescribe(this))
				.setCancelable(false).setPositiveButton(R.string.update_ignore, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						UpdatePrefs.setHomeTipTime(SettingActivity.this, System.currentTimeMillis());
						dialog.cancel();
					}
				}).setNegativeButton(R.string.update_now, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.cancel();
						Toast.makeText(SettingActivity.this, "开始下载", 0);
						startService(new Intent(SettingActivity.this, DownloadAPK.class));
					}
				}).show();

	}

	private void findViewByIds() {
		findViewById(R.id.set_regdiv).setOnClickListener(this);
		findViewById(R.id.my_addres).setOnClickListener(this);
		if (IAskMyActionPre.getLogOn(this).length() > 0) {
			((TextView) findViewById(R.id.unregister)).setText("用户信息");
		}
				set_newversion = (TextView) findViewById(R.id.set_newversion);
		set_newversion.setText("v"+MobileUtils.getStringVersion()+"");
		findViewById(R.id.set_ibb).setOnClickListener(this);
		findViewById(R.id.set_psuh_rl).setOnClickListener(this);
		set_psuh_rl = (RelativeLayout)findViewById(R.id.set_psuh_rl);
		findViewById(R.id.check_newversion).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//监测新版本
				CheckVersionUpgrade();
			}
		});
		unregister = (TextView) findViewById(R.id.unregister);
		now_state=(TextView) findViewById(R.id.now_state);
		getData(); //获取当前状态
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.my_addres:
			go(MyAddressActivity.class);
//			go(StateSelectActivity.class);
			break;
		case R.id.set_regdiv:
			go(ChangeStateActivity.class);
			break;
		case R.id.two_email:
			String[] receiver = new String[] { "lmyr@7500.com.cn" };
			String subject = "";
			String res = "";

			Intent email = new Intent(Intent.ACTION_SEND);
			email.setType("message/rfc822");
			// 设置邮件发收人
			email.putExtra(Intent.EXTRA_EMAIL, receiver);
			// 设置邮件标题
			email.putExtra(Intent.EXTRA_SUBJECT, subject);
			// 设置邮件内容
			email.putExtra(Intent.EXTRA_TEXT, res);
			// 调用系统的邮件系统
			startActivity(Intent.createChooser(email, "请选择邮件发送软件"));
			break;
		case R.id.two_phone:
			Intent intent_phone = new Intent(Intent.ACTION_CALL,
					Uri.parse("tel:010-57302471"));
			startActivity(intent_phone);
			break;
		case R.id.set_aboutus_div:
			// 免责声明
			Intent intentAbout = new Intent(this, SetDeclare.class);
			intentAbout.putExtra("id", R.id.set_aboutus_div);
			startActivity(intentAbout);
			break;
		case R.id.setting_aboutus:
			// 关于我们
			Intent intent_AboutUs = new Intent(this, SetDeclare.class);
			intent_AboutUs.putExtra("COMEFROM","setting_aboutus");
			startActivity(intent_AboutUs);
			break;
		case R.id.set_ibb:
			this.finish();
			go(MybabyActivity.class);
			break;
		case R.id.btnLoginRegist:
			goRegActivity();
			break;
		case R.id.btnLogon:
			showDialog(DIALOG_EXIT);
			break;
		case R.id.set_psuh_rl:
			go(PushSettingActivity.class);
			break;
		default:
			break;
		}
	}
	
	private void goRegActivity(){
		Intent intent = new Intent(this, RegAndLoginActivity.class);
		intent.putExtra("from", TAG);
		startActivity(intent);
		finish();
	}
	/**
	 * 检测版本升级
	 */
	private void CheckVersionUpgrade() {
		versionUdgrateUtil = new VersionUdgrateUtil(this,true);
		versionUdgrateUtil.checkVersionUdgrate();
	}
	private static final int DIALOG_EXIT = 1;
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_EXIT:
			Dialog dialog = new AlertDialog.Builder(this).setMessage("退出登录后不会删除任何历史数据，下次登录后依然可以使用本账号。").setPositiveButton("退出登录", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					mTokenKeeper.clearAccessToken(SettingActivity.this);
					AppManager.getAppManager().finishAllActivity();
					goRegActivity(); 
				
				}
			}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			}).create();
			return dialog;

		default:
			return super.onCreateDialog(id);
		}
	}


	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
//			go(HomeActivity.class);
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}


	class OurAppAdapter extends BaseAdapter {
		
		List<AppBean> list = new ArrayList<AppBean>();
		
		public OurAppAdapter() {
			AppBean app = new AppBean();
			app.setName("新锐财经");
			app.setDescription("随时随地体验新锐财经");
			app.setFile_id(25);
			app.setImgurl("http://lmyrst.oss-cn-beijing.aliyuncs.com/xinruicaijing.png");
			app.setUrl("http://itunes.apple.com/us/app/id548248143?l=zh&ls=1&mt=8&type=2");
			list.add(app);
		}

		public void addBean(List<AppBean> beans){
			if (beans != null) {
				for (AppBean appBean : beans) {
					list.add(appBean);
				}
			}
		}
		
		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			OurAppHolder holder = null;
			if (convertView == null) {
				convertView = layoutInflater.inflate(R.layout.set_ourapp_item, null);
				holder = new OurAppHolder();
				holder.image = (ImageView) convertView.findViewById(R.id.set_ourapp_img);
				holder.name = ((TextView) convertView.findViewById(R.id.set_outapp_name));
				holder.desciption = ((TextView) convertView.findViewById(R.id.set_outapp_descrip));
				convertView.setTag(holder);
			} else {
				holder = (OurAppHolder) convertView.getTag();
			}

			AppBean bean = (AppBean) getItem(position);
			mBmpUtils.display(holder.image, bean.getImgurl());
			holder.name.setText(bean.getName());
			holder.desciption.setText(bean.getDescription());
			return convertView;
		}


	}

	class OurAppHolder {
		ImageView image;
		TextView name;
		TextView desciption;

	}

	class OtherAppHolder {

		com.ykdl.member.kid.widget.AsyncImageView image1;
		TextView name1;

		com.ykdl.member.kid.widget.AsyncImageView image2;
		TextView name2;

		com.ykdl.member.kid.widget.AsyncImageView image3;
		TextView name3;

		com.ykdl.member.kid.widget.AsyncImageView image4;
		TextView name4;

	}

	class OtherAppAdapter extends BaseAdapter {
		int mycount = 4;

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mycount;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			OtherAppHolder holer = null;
			if (convertView == null) {
				convertView = layoutInflater.inflate(R.layout.set_otherapp_item, null);
				holer = new OtherAppHolder();
				holer.image1 = (com.ykdl.member.kid.widget.AsyncImageView) convertView
						.findViewById(R.id.set_otherapp_img1);
				holer.name1 = ((TextView) convertView.findViewById(R.id.set_otherapp_tip1));

				holer.image2 = (com.ykdl.member.kid.widget.AsyncImageView) convertView
						.findViewById(R.id.set_otherapp_img2);
				holer.name2 = ((TextView) convertView.findViewById(R.id.set_otherapp_tip2));

				holer.image3 = (com.ykdl.member.kid.widget.AsyncImageView) convertView
						.findViewById(R.id.set_otherapp_img3);
				holer.name3 = ((TextView) convertView.findViewById(R.id.set_otherapp_tip3));

				holer.image4 = (com.ykdl.member.kid.widget.AsyncImageView) convertView
						.findViewById(R.id.set_otherapp_img4);
				holer.name4 = ((TextView) convertView.findViewById(R.id.set_otherapp_tip4));

				convertView.setTag(holer);

			} else {
				holer = (OtherAppHolder) convertView.getTag();
			}

			holer.image1.setVisibility(View.VISIBLE);
			holer.name1.setVisibility(View.VISIBLE);

			holer.image2.setVisibility(View.INVISIBLE);
			holer.name2.setVisibility(View.INVISIBLE);

			holer.image3.setVisibility(View.INVISIBLE);
			holer.name3.setVisibility(View.INVISIBLE);

			holer.image4.setVisibility(View.INVISIBLE);
			holer.name4.setVisibility(View.INVISIBLE);

			int realpos = position * 4;


			if (position == getCount() - 1) {
				convertView.setBackgroundResource(R.drawable.set_appitem_bot);
			} else {
				convertView.setBackgroundResource(R.drawable.set_appitem_mid);
			}

			return convertView;
		}


	}

	private class AppListTag implements ITag<AppListBean>{

		@Override
		public void refreshUI(AppListBean t, DataState ds) {
			if (t != null) {
				List<AppBean> beans = t.getApps();
				ourappadapter.addBean(beans);
				ourappadapter.notifyDataSetChanged();
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			return false;
		}

		@Override
		public void refreshCancel() {
			
		}
		
	}
	

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 100 && RESULT_OK == resultCode) {
				((TextView) findViewById(R.id.unregister)).setText("用户信息");
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		try {
			AppBean bean = (AppBean) ourappadapter.getItem(position);
			Intent intent = new Intent();
			intent.setAction("android.intent.action.VIEW");
			String url = bean.getUrl();
			if (!url.startsWith("http")) {
				url = "http://" + url;
			}
			Uri content_url = Uri.parse(url);
			intent.setData(content_url);
			startActivity(intent);
		} catch (Exception ee) {

		}
	}
	
	/**
	 * 获取当前状态
	 */
	public void getData() {
		showProgress("正在加载中,请稍等...");
		String pageurl = KidConfig.GET_MYSELF;
		HttpParameters parameterss = new HttpParameters();
		HttpBaseRequest request = Wxxr.getInstance().getRequest(pageurl,
				parameterss, null);
		TaskManager.startHttpRequest(request, new getDataTag(),
				GetUser_ScoreBean.class);
	}

	class getDataTag implements ITag {

		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			finishProgress();
			if (t instanceof GetUser_ScoreBean) {
				GetUser_ScoreBean beans = (GetUser_ScoreBean) t;
				if(beans!=null){
					if(beans.getActor_info().getStatus()==1){ //#c1c0c0
						now_state.setText("孕期");
					}else if(beans.getActor_info().getStatus()==3){
						now_state.setText("6岁+");
					}else{
						now_state.setText("0~6岁");
					}
				}
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			finishProgress();
			Toast.makeText(mContext, "加载失败", 1).show();
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
		}
	}
	
}
